package com.example.demo.socket.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: htc
 * @date: Created in 10:51 2018/11/29.
 */
public class ServerDemo {
    private static Logger log = LoggerFactory.getLogger(ServerDemo.class);
    /**
     * 监听指定端口
     */
    public static final Integer PORT = 9001;

    public static void init() {
        try {
            //创建一个ServerSocket，port是客户端的端口
            ServerSocket serverSocket = new ServerSocket(PORT);
            while (true) {
                //从请求队列中取出链接,如果只接受一次则不用使用while循环
                Socket socket = serverSocket.accept();
                //从socket中获取输入流，获取客户端信息（字符流读取方式）
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String clientContent = input.readLine();
                //接下来可以对信息进行操作，
                System.out.println(clientContent);

                //初始化输出流，回复客户端
                PrintStream out = new PrintStream(socket.getOutputStream());
                //获取键盘输出的内容
                String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
                //将信息发送给客户端
                out.println("open");

                //guanbi
                out.close();
                input.close();
            }
        } catch (Exception e) {
            log.error("server error: " + e);
        }
    }

    /**
     * 字节流读取数据
     *
     * @param inputStream
     */
    private static void readWithReader(InputStream inputStream) {
        BufferedReader input = new BufferedReader(new InputStreamReader(inputStream));
        String content = null;
        try {
            content = input.readLine();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
            try {
                input.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
        System.out.println(content);
    }

    /**
     * 字符流读取数据
     *
     * @param inputStream
     */
    private static void readWithStream(InputStream inputStream) {
        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        try {
            while ((len = inputStream.read(bytes)) != -1) {
                //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                sb.append(new String(bytes, 0, len, "UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(sb);
    }

    public static void main(String[] args) {
        init();
    }
}
